package com.sayice.gomoku.web;

import com.alibaba.fastjson.JSON;
import com.sayice.gomoku.game.Game;
import com.sayice.gomoku.pojo.Board;
import com.sayice.gomoku.pojo.User;
import com.sayice.gomoku.service.BoardService;
import com.sayice.gomoku.service.UserService;
import com.sayice.gomoku.service.impl.BoardServiceImpl;
import com.sayice.gomoku.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 处理用户业务请求
 */
@WebServlet(urlPatterns = "/userServlet")
public class UserServlet extends BaseServlet {
    private final UserService userService = new UserServiceImpl();
    private final BoardService boardService = new BoardServiceImpl();
    
    /**
     * 检查用户名是否已存在
     */
    protected void checkExists(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("收到 checkExists 请求");
        String name = req.getParameter("name").trim();
        boolean existsName = userService.existsName(name);
        resp.getWriter().write(JSON.toJSONString(existsName));
    }
    
    /**
     * 注册
     */
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name").trim();
        String password = req.getParameter("password").trim();
        final String passwdPattern = "^[0-9a-zA-Z]{6,}$";
        if ("".equals(name)) {
            req.setAttribute("msg", "用户名不能为空！");
            req.getRequestDispatcher("/pages/user/register.jsp").forward(req, resp);
            return;
        }
        if (userService.existsName(name)) {
            req.setAttribute("msg", "用户名已存在！");
            req.setAttribute("name", name);
            req.getRequestDispatcher("/pages/user/register.jsp").forward(req, resp);
            return;
        }
        if ("".equals(password)) {
            req.setAttribute("msg", "密码不能为空！");
            req.setAttribute("name", name);
            req.getRequestDispatcher("/pages/user/register.jsp").forward(req, resp);
            return;
        }
        if (!password.matches(passwdPattern)) {
            req.setAttribute("msg", "密码不合法！");
            req.setAttribute("name", name);
            req.getRequestDispatcher("/pages/user/register.jsp").forward(req, resp);
            return;
        }
        System.out.println("用户注册成功");
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        userService.register(user);
        // 设置为已购买默认棋盘
        boardService.buy(userService.getUserByName(name).getId(), 1);
        // 设置当前使用棋盘为默认棋盘
        userService.setDefaultBoard(userService.getUserByName(name).getId(), 1);
        req.getRequestDispatcher("/pages/user/registerSuccess.jsp").forward(req, resp);
    }
    
    /**
     * 登录
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name").trim();
        if (Game.playerMap.containsKey(name)) {
            req.setAttribute("msg", "已在对战系统中，请勿重复进入");
            req.setAttribute("name", name);
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
            return;
        }
        String password = req.getParameter("password").trim();
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        User loginUser = userService.login(user);
        if (loginUser == null) {
            req.setAttribute("msg", "用户名或密码错误！");
            req.setAttribute("name", name);
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
            return;
        }
        System.out.println("用户登录成功");
        req.setAttribute("user", loginUser);
        req.getSession().setAttribute(name, loginUser.getId());
        req.getRequestDispatcher("/pages/play/play.jsp").forward(req, resp);
    }
    
    /**
     * 获取使用的棋盘
     */
    protected void getBoard(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int id = Integer.parseInt(req.getParameter("id").trim());
        User user = userService.getUserById(id);
        Board board = boardService.getBoard(user.getBoardId());
        String boardName = board == null ? "" : board.getName();
        resp.getWriter().write(JSON.toJSONString(boardName));
    }
    
    /**
     * 设置使用的棋盘
     */
    protected void useBoard(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int userId = Integer.parseInt(req.getParameter("userId").trim());
        int boardId = Integer.parseInt(req.getParameter("boardId").trim());
        // 判断是否已购买
        if (boardService.bought(boardId, userId)) {
            userService.setBoard(userId, boardId);
            resp.getWriter().write(JSON.toJSONString(true));
        }
    }
    
    /**
     * 切换使用的棋盘
     */
    protected void switchBoard(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int id = Integer.parseInt(req.getParameter("id").trim());
        User user = userService.getUserById(id);
        List<Board> boards = boardService.getUserBoards(id);
        if (boards.size() == 1) {
            return;
        }
        Board currentBoard = boards.stream()
                .filter((Board b) -> b.getId() == user.getBoardId())
                .collect(Collectors.toList()).get(0);
        int index = boards.indexOf(currentBoard);
        if (++index == boards.size()) {
            index = 0;
        }
        Board board = boards.get(index);
        userService.setBoard(id, board.getId());
        resp.getWriter().write(JSON.toJSONString(board.getName()));
    }
    
    /**
     * 进入个人中心
     */
    protected void enterCenter(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name").trim();
        if (!Game.playerMap.containsKey(name)) {
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
            return;
        }
        System.out.println(name + "进入个人中心");
        User user = userService.getUserByName(name);
        List<Board> userBoards = boardService.getUserBoards(user.getId());
        List<Board> boards = boardService.getBoards();
        req.setAttribute("user", user);
        req.setAttribute("userBoards", userBoards);
        req.setAttribute("boards", boards);
        req.getRequestDispatcher("/pages/user/personalCenter.jsp").forward(req, resp);
    }
}
